package top.kaoshanji.p3ch12b;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;

/**
 * 代码清单-p3ch12b-16页a：请求头referer有值才显示图片
 * @author kaoshanji
 * ^_^
 * create time 2025/4/9 11:06
 */
@WebServlet(urlPatterns = {"/getImage"})
public class ImageServlet extends HttpServlet {

    private static final long serialVersionUID = -99L;

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String referrer = req.getHeader("referer"); // 他二大爷的...请求头属性和定义的变量不一样....
        if (referrer != null) {
            String imageId = req.getParameter("id");

            String imageDirectory = Constant.LOCAL_ROOT_PATH.concat("image");
            // String imageDirectory = req.getServletContext().getRealPath("/WEB-INF/image");
            File file = new File(imageDirectory, imageId + ".jpg");

            if (file.exists()) {
                resp.setContentType("image/jpg");
                byte[] buffer = new byte[1024];
                FileInputStream fis = null;
                BufferedInputStream bis = null;
                try {
                    fis = new FileInputStream(file);
                    bis = new BufferedInputStream(fis);

                    OutputStream os = resp.getOutputStream();
                    int i = bis.read(buffer);
                    while (i != -1) {
                        os.write(buffer, 0, i);
                        i = bis.read(buffer);
                    }
                } catch (IOException e) {
                    System.out.println(e.toString());
                } finally {
                    if (bis != null) {
                        bis.close();
                    }
                    if (fis != null) {
                        fis.close();
                    }
                }
            }
        }
    }
}
